package com.hs.shirodemo2.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.shirodemo2.constant.CommonConstant;
import com.hs.shirodemo2.entity.SysUser;
import com.hs.shirodemo2.entity.UserInfo;
import com.hs.shirodemo2.mapper.SysUserMapper;
import com.hs.shirodemo2.service.SysPermissionService;
import com.hs.shirodemo2.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public SysUser findByUsername(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public void add(SysUser entity) {
        SysUser sysUser = findByUsername(entity.getUsername());
        //后台校验，保证安全性，防止第三方工具注册（PostMan）
        if (sysUser == null) {
            entity.setUserpwd(CommonConstant.PASSWORD_DEFAULT);
            entity.setUserpwd(new SimpleHash("md5",entity.getUserpwd(),entity.getSalt(),2).toHex());
            sysUserMapper.insert(entity);
            // 判断用户角色列表是否为空，如果不为空，则在用户和角色中间表插入数据
            // CollectionUtils是Spring提供处理集合的工具类
            if(!CollectionUtils.isEmpty(entity.getRoleIdList())){
                sysUserMapper.insertUserRole(entity);
            }
        }
    }

    @Override
    public void edit(SysUser entity) {
        SysUser sysUser = findByUsername(entity.getUsername());
        if (sysUser != null) {
            if(!sysUser.getUserpwd().equals(entity.getUserpwd())){
                entity.setUserpwd(new SimpleHash("md5",entity.getUserpwd(),entity.getSalt(),2).toHex());
            }
            sysUserMapper.update(entity);
            // 先删除用户的所有角色，然后再新增
            if(entity.getRoleIdList() != null){
                sysUserMapper.deleteUserRoleById(entity.getId());
                // 添加
                if(!CollectionUtils.isEmpty(entity.getRoleIdList())){
                    sysUserMapper.insertUserRole(entity);
                }
            }
        }
    }

    @Override
    public void remove(Integer id) {
        sysUserMapper.delete(id);
    }

    @Override
    public void removeBatch(Integer[] ids) {
        sysUserMapper.deleteBatch(ids);
    }

    @Override
    public List<SysUser> find(SysUser entity) {
        return sysUserMapper.select(entity);
    }

    @Override
    public Map<String, Object> findPage(Integer pageNum, Integer pageSize, SysUser entity) {
        //分页业务实现
        PageHelper.startPage(pageNum, pageSize);

        List<SysUser> list = sysUserMapper.select(entity);

        PageInfo<SysUser> pageInfo = new PageInfo<>(list);

        /*
         * 把前台需要的数据反馈
         * 1、当前页面数据（数据列表）
         * 2、此次查询的总记录数
         */
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put(CommonConstant.PAGE_LIST, list);
        pageMap.put(CommonConstant.PAGE_TOTAL, pageInfo.getTotal());

        return pageMap;
    }

    @Override
    public SysUser findById(Integer id) {
        return sysUserMapper.selectById(id);
    }

    /**
     * 登录
     * 1.根据用户提供用户名（用户标识），到数据库中查询相关记录
     * 2.判断查询到的用户是否为null
     * 3.如果为null，表示当前用户提供的用户名有误
     * 4.如果不为null，根据用户提供的密码（用户凭证）比对数据库中存储的密码
     * 5.如果不一致表示用户提供的密码有误
     * 6.如果一致返回UserInfo对象
     */
    @Override
    public UserInfo login(String username, String userpwd) {
//        SysUser sysUser = sysUserMapper.selectByUsername(username); // 根据用户名查询用户
//        if(sysUser != null){
//            if(userpwd.equals(sysUser.getUserpwd())){ // 如果用户存在，比对密码
//                UserInfo userInfo = new UserInfo();
//                //spring中提供了一个工具类BeanUtils，提供属性值复制功能
//                //copyProperties(源对象, 目标对象)
//                //要求：属性名称保持一致
//                BeanUtils.copyProperties(sysUser, userInfo);
//                // 登录成功之后，查询一次用户的权限
//                List<SysPermission> permisssionList = sysPermissionService.findPermissionByUserId(userInfo.getId());
//                userInfo.setPermissionList(permisssionList);
//                return userInfo;
//            }
//        }
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            try{
                subject.login(new UsernamePasswordToken(username,userpwd));
            }catch (AuthenticationException e){
                System.out.println("登录失败");
            }
        }
        return (UserInfo) subject.getPrincipal();
    }
}